//
//  VideoDownViewController.m
//  Cook
//
//  Created by 0.0 on 15-4-22.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "VideoDownViewController.h"
#import "DownTableViewCell.h"
#import "DownLoadDataBase.h"
#import "DownLoadModel.h"
#import "DownLoad.h"
#import "PlayVideoViewController.h"

@interface VideoDownViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
{
   
    NSString *deleteVideoName; // 临时保存用户长按手势要删除的视频
    NSString *deleteDownCacheFileName; // 下载进度文件
    
//    NSTimer *_timer;
//    UIAlertView *_alertView;
    
    
    
//    NSTimer *_stateTimer;
    
}

@property (nonatomic, retain) NSMutableArray *tableArray;
@property (nonatomic, retain) NSMutableArray *cellArray;
@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *timerArray; // 存放所有对象和cell数组的数组

@property (nonatomic, retain) DownLoadModel *reDownmodel;
@property (nonatomic, retain) NSString *isOpenDown; // 是否正在下载

@property (nonatomic, retain) NSTimer *stateTimer;


@end

@implementation VideoDownViewController

- (void)dealloc
{
    [_tableArray release];
    [_cellArray release];
    [_timerArray release];
    [_reDownmodel release];
    [_isOpenDown release];
    [_tableView release];
    [_stateTimer release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeNum" object:nil];
    
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.tableArray = [NSMutableArray array];
        self.cellArray = [NSMutableArray array];
        self.timerArray = [NSMutableArray array];
        
    }
    
    return self;
}

#pragma mark - 视图将要出现
- (void)changeNum:(NSNotification *)center
{
    NSDictionary *dic = [center userInfo];
    
    self.isOpenDown = dic[@"key"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.isOpenDown = @"0";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNum:) name:@"changeNum" object:nil];
    
    
    // 从数据库读取数据
    NSArray *array = [self getDataFromDataBase];
    if (0 == [array count]) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"您没下载过视频" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        view.tag = 105;
        [view show];
        [view release];
    }
    //    self.cellArray = [NSMutableArray arrayWithCapacity:[array count]];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.navigationItem.title = @"视频列表";
    [self creatBackground];
    [self createTabelView];
    [self createLongPress];
    
    [self getDataFromDataBase];
    
    
    
}

#pragma mark - 创建背景
- (void)creatBackground
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"fourthBarBacground.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
}

#pragma mark - 创建TabelView
- (void)createTabelView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 49 - 64) style:UITableViewStylePlain];
    [_tableView setBackgroundColor:[UIColor clearColor]];
        [_tableView registerClass:[DownTableViewCell class] forCellReuseIdentifier:@"cell1"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [self.view addSubview:_tableView];
    [_tableView release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    DownTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
    
    DownLoadModel *model = [self.tableArray objectAtIndex:indexPath.row];
    // 从数组里获取当前进度条的值
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.videoImageView sd_setImageWithURL:[NSURL URLWithString:model.videoImageURL] placeholderImage:image];
    [cell.videoName setText:model.vegetableName];
    [cell.videoDownStateNum setText:@""];
    
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSString *statePath = [NSString stringWithFormat:@"%@/%@", libraryPath, model.vegetableName];
    NSString *stateNum = [NSString stringWithContentsOfFile:statePath encoding:NSUTF8StringEncoding error:nil];
    cell.progress.progress = stateNum.floatValue;
    [cell.videoDownStateNum setText:[NSString stringWithFormat:@"%.2f%%", stateNum.floatValue * 100]];
    
    cell.backgroundColor = [UIColor clearColor];
    cell.videoName.textColor = [UIColor whiteColor];
    cell.videoDownStateNum.textColor = [UIColor whiteColor];
    
    [self.cellArray addObject:cell];
//    [cell release];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DownLoadModel *model = [self.tableArray objectAtIndex:indexPath.row];
    self.reDownmodel = model;
    
    NSString *downStateNum = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    downStateNum = [NSString stringWithFormat:@"%@/%@", downStateNum, _reDownmodel.vegetableName];
    NSString *downNum = [NSString stringWithContentsOfFile:downStateNum encoding:NSUTF8StringEncoding error:nil];
    
    
    if (downNum.floatValue == 1.000000) {
        
        
        PlayVideoViewController *play = [[PlayVideoViewController alloc] init];
        play.hidesBottomBarWhenPushed = YES;
        
        play.downModel = model;
        play.goal = self;
        
        
        [self.navigationController pushViewController:play animated:YES];
        [play release];
        
    }
    // 判断当前没有视频正在下载
    else if ([self.isOpenDown isEqualToString:@"0"]) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否重新下载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        view.tag = 101;
        [view show];
        [view release];
        
    }
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.cellArray count] != 0) {
    DownLoadModel *model = [self.tableArray objectAtIndex:indexPath.row];
    NSString *num = [self downNumWithFileName:model.vegetableName];
    
    if (num.floatValue == 1.0) {
        return YES;
    }
    }
    return NO;
}
//
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"确认删除此视频?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    view.tag = 103;
    [view show];
    [view release];
    DownLoadModel *model = [self.tableArray objectAtIndex:indexPath.row];
    deleteVideoName = model.videoName;
    deleteDownCacheFileName = model.vegetableName;
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *my = [[tableView indexPathsForVisibleRows] lastObject];
    
    if (indexPath.row == my.row) {
        [self getProgressData];
    }
}


#pragma mark - 删除视频
- (BOOL)removeVideo:(NSString *)videoName
{
    // 删除本地对应的视频
    
    // 因为视频文件有2个一个A 一个B, 所以我们要截取前面的名字
    NSString *forName = [self getNameFromVideoName:(NSString *)videoName];
    
    NSString *videoPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    videoPath = [NSString stringWithFormat:@"%@/%@", videoPath, @"video"];
    
    NSFileManager *man = [NSFileManager defaultManager];
    
    
    // 删除本地下载进度文件
    NSString *downCache = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    downCache = [NSString stringWithFormat:@"%@/%@", downCache, deleteDownCacheFileName];
    
    if ([man fileExistsAtPath:downCache]) {
        [man removeItemAtPath:downCache error:nil];
        NSLog(@"删除本地文件");
    }
    
    
    
    // 拼接好视频名字然后删除
    NSString *videoA = [NSString stringWithFormat:@"%@A.mp4", forName];
    NSString *goal = [NSString stringWithFormat:@"%@/%@", videoPath, videoA];
    if ([man fileExistsAtPath:goal]) {
        [man removeItemAtPath:goal error:nil];
        NSString *videoB = [NSString stringWithFormat:@"%@B.mp4", forName];
        NSString *goal2 = [NSString stringWithFormat:@"%@/%@", videoPath, videoB];
        if ([man fileExistsAtPath:goal2]) {
            [man removeItemAtPath:goal2 error:nil];
            NSLog(@"删除成功");
        }
    }
    
    // 先删除数据库中得数据
    [DownLoadDataBase deleteWithTable:videoName];
    
    // 删除后重新请求一遍数据并且刷新
    [self getDataFromDataBase];
//    [_tableView reloadData];
    
    return YES;
}


#pragma mark - 得到视频名字
- (NSString *)getNameFromVideoName:(NSString *)videoName
{
    NSInteger count = [videoName length];
    NSString *name = [videoName substringToIndex:count - 5];
    return name;
}

#pragma mark - 添加长按手势
- (void)createLongPress
{
    UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    longPressGr.minimumPressDuration = 0.5f;
    longPressGr.numberOfTouchesRequired = 1;
    [_tableView addGestureRecognizer:longPressGr];
    [longPressGr release];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [longPress locationInView:_tableView];
        
        NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:point];
        
        if (indexPath != nil) {
            
            DownLoadModel *model = [self.tableArray objectAtIndex:indexPath.row];
            deleteVideoName = model.videoName;
            deleteDownCacheFileName = model.vegetableName;
            
            NSString *num = [self downNumWithFileName:model.vegetableName];
            if (num.floatValue == 1.0) {
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"确认删除此视频?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                view.tag = 102;
                [view show];
                [view release];
            }
            
        }
        
    }
}

#pragma mark - 提示view点击事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (101 == alertView.tag) {
        if (1 == buttonIndex) {
            [self removeVideo:_reDownmodel.videoName];
            DownLoad *down = [[DownLoad alloc] init];
            // 将视频路径读取出来, 然后拆分之后合并一个数组传递给下载功能进行下载.
            NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
            savePath = [NSString stringWithFormat:@"%@/%@", savePath, @"video"];
            
            NSArray *array = [_reDownmodel.videoURLPath componentsSeparatedByString:@"$"];
            [down downloadFileURL:array savePath:savePath num:0 imageURL:_reDownmodel.videoImageURL vegetableName:_reDownmodel.vegetableName];
        }
    }
    
    if (102 == alertView.tag || 103 == alertView.tag) {
        if (buttonIndex == 1) {
            [self removeVideo:deleteVideoName];
//            [_tableView reloadData];
//            [self getProgressData];
        }
    }
    
    // 当前视频列表为空得话, 返回
    if (105 == alertView.tag) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma 获得进度条的数值
- (void)getProgressData
{
    for (int i = 0; i < [self.cellArray count]; i++) {
        DownLoadModel *model = [self.tableArray objectAtIndex:i];
        DownTableViewCell *cell = [self.cellArray objectAtIndex:i];
        NSString *vegetable = model.vegetableName;
        NSDictionary *dic = @{@"vegetableName":vegetable, @"cell":cell}; // 通过这个key的value去本地对应的找到num值
        [self.timerArray addObject:dic];
    }
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.timerArray, @"allData", nil];
    self.stateTimer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(changeDown:) userInfo:dic repeats:YES];
}

#pragma mark - 视频下载进度改变
- (void)changeDown:(NSTimer *)time
{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
        NSMutableArray *allArray = [[time userInfo] objectForKey:@"allData"];
        
        for (NSDictionary *dic in allArray) {
            NSString *vegetableName = dic[@"vegetableName"];
            NSString *vePath = [NSString stringWithFormat:@"%@/%@", path, vegetableName];
            NSString *strNum = [NSString stringWithContentsOfFile:vePath encoding:NSUTF8StringEncoding error:nil];
            CGFloat stateNum = strNum.floatValue;
            DownTableViewCell *cell = dic[@"cell"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                cell.progress.progress = stateNum;
                [cell.videoDownStateNum setText:[NSString stringWithFormat:@"%.2f%%", stateNum * 100.0]];
                
            });
        }
    });
}

#pragma mark - 从数据库中取出已经下载的视频
- (NSArray *)getDataFromDataBase
{
    [self.tableArray removeAllObjects];
    NSArray *array = [DownLoadDataBase searchNovel];
    for (DownLoadModel *model in array) {
        [self.tableArray addObject:model];
    }
    
    [self.cellArray removeAllObjects];
    
    [_tableView reloadData];
    
    return array;
}


#pragma mark - 获得下载视频值的文件的值
- (NSString *)downNumWithFileName:(NSString *)vegetableName
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    path = [NSString stringWithFormat:@"%@/%@", path, vegetableName];
    NSString *num = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    return num;
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self setEditing:NO];
    [self.tableView setEditing:NO];
    
    
    [super viewWillDisappear:animated];
    if (_stateTimer != nil && [self.isOpenDown isEqualToString:@"0"]) {
        [_stateTimer invalidate];
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
